package com.one.shopping.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.one.shopping.R;
import com.one.shopping.adapter.ShopGoodsAdapter;
import com.one.shopping.api.OneApi;
import com.one.shopping.entity.Goods;
import com.one.shopping.entity.Result;
import com.one.shopping.ui.activity.ShoppingCartActivity;
import com.one.shopping.ui.activity.TabHostActivity;
import com.one.shopping.ui.baseFragment.BaseFragment;
import com.one.shopping.util.GsonUtils;

import org.apache.http.Header;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 柯尊诚
 * @version 1.0
 * @date 创建时间：2016/1/13 00:28
 */
public class ShopGoodsFragment extends BaseFragment{

    protected static final int ShoppingcartCode = 0x1001;
    private List<Goods> shoppingcartList;
    private ListView goodsLV;
    public static TextView totalTv;
    private Button goodBtn;
    private List<Goods> good_List;
    private ShopGoodsAdapter adapter;
    private Button shoppingcartBtn;
    private EditText conditionEt;
    private SharedPreferences mySharedPreferences;
    public static double total=0;
    private SharedPreferences.Editor editor;
    public static View.OnClickListener goodBtnOnClickListener;
    private EditText queryField;
    private ImageView scanBtn;

    private static final String SCAN_INTENT = "com.google.zxing.client.android.SCAN";
    private static final String SCAN_RESULT = "SCAN_RESULT";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_goods, container, false);

        init(view);
        clearShoppingCart();

        (view.findViewById(R.id.shoppingcart_layout)).getBackground().setAlpha(100);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        ((TabHostActivity)getActivity()).isVisibleTitle(false);
//        ((TabHostActivity)getActivity()).isVisibleQuery(true);
//        ((TabHostActivity)getActivity()).isVisibleScanFind(true);
        isVisibleQuery(true);
        isVisibleScanFind(true);
    }
    /**
     * 是否显示查询按钮
     */
    public void isVisibleQuery(boolean tag) {
        ImageView queryBtn = (ImageView) getActivity().findViewById(R.id.main_query_btn_iv);
        if (queryBtn != null) {
            if (tag) {
                queryBtn.setVisibility(View.VISIBLE);
                queryBtn.setOnClickListener(goodBtnOnClickListener);
            }
            else
                queryBtn.setVisibility(View.GONE);
        }
    }

    /**
     * 是否显示扫描按钮和输入框
     */
    public void isVisibleScanFind(boolean tag) {
        scanBtn = (ImageView) getActivity().findViewById(R.id.main_scan_btn_iv);
        queryField = (EditText) getActivity().findViewById(R.id.main_query_values_et);
        if (scanBtn != null && queryField != null) {
            if (tag) {
                scanBtn.setVisibility(View.VISIBLE);
                queryField.setVisibility(View.VISIBLE);
                //扫描点击事件
                scanBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intentScan = new Intent(SCAN_INTENT);
                        intentScan.addCategory(Intent.CATEGORY_DEFAULT);

                        startActivityForResult(intentScan, 100);
                    }
                });
            } else {
                scanBtn.setVisibility(View.GONE);
                queryField.setVisibility(View.GONE);
            }
        }
    }

    private void init(View view) {
        //实例化SharedPreferences对象
        mySharedPreferences= getActivity().getSharedPreferences("shoppingcart", Activity.MODE_PRIVATE);
        // 实例化SharedPreferences.Editor对象
        editor = mySharedPreferences.edit();
        conditionEt = (EditText) view.findViewById(R.id.et_condition);
        goodBtn = (Button) view.findViewById(R.id.btn_goods);
        shoppingcartBtn = (Button) view.findViewById(R.id.btn_shoppingcart);

        totalTv = (TextView) view.findViewById(R.id.totalTV);

        goodsLV = (ListView) view.findViewById(R.id.goods_list);

        goodBtnOnClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
//				if (conditionEt.getText().toString().trim()=="") {
//					queryGoods();
//					Total();
//				}else{
//                queryGoodsByCondition(conditionEt.getText().toString().trim());
                queryGoodsByCondition(queryField.getText().toString().trim());
                Total();
//				}
            }
        };
        goodBtn.setOnClickListener(goodBtnOnClickListener);



        shoppingcartBtn= (Button) view.findViewById(R.id.btn_shoppingcart);
        shoppingcartBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                shoppingcartList();
                Intent intent = new Intent(getActivity(),ShoppingCartActivity.class);
                intent.putExtra("shoppingcartList", (Serializable)shoppingcartList);
                startActivityForResult(intent, ShoppingcartCode);
            }
        });
    }

    /**
     * 获取购物车列表到shoppingcartList
     */
    public void shoppingcartList(){
        shoppingcartList=new ArrayList<Goods>();
        String id = mySharedPreferences.getString("id","");
        String name = mySharedPreferences.getString("name", "");
        String image = mySharedPreferences.getString("image", "");
        String price = mySharedPreferences.getString("price", "");
        String stock = mySharedPreferences.getString("stock", "");
        Log.i("hjw", "stock="+stock);
        String quantity = mySharedPreferences.getString("quantity", "");
        if (id!="") {
            String ids[] = id.split(",");
            String names[] = name.split(",");
            String images[] = image.split(",");
            String prices[] = price.split(",");
            String stocks[] = stock.split(",");
            for (int i = 0; i < ids.length; i++) {
                Goods good = new Goods();
                good.setId(ids[i]);
                good.setName(names[i]);
                good.setImage(images[i]);
                good.setPrice(prices[i]);
                good.setStock(Integer.valueOf(stocks[i]));
                shoppingcartList.add(good);
            }
        }
    }

    /**
     * 计算总金额
     */
    public void Total(){
        total=0;
        String id = mySharedPreferences.getString("id","");
        String price = mySharedPreferences.getString("price", "");
        String quantity = mySharedPreferences.getString("quantity", "");
        if (id!="") {
            String ids[] = id.split(",");
            String prices[] = price.split(",");
            String quantitys[] = quantity.split(",");
            for (int i = 0; i < ids.length; i++) {
                total=total+(Double.valueOf(prices[i]) * Integer.valueOf(quantitys[i]));
            }
        }
        BigDecimal bd = new BigDecimal(total);
        bd=bd.setScale(2, BigDecimal.ROUND_UP);
        totalTv.setText("总金额(￥):"+bd+"");
    }

    /**
     * 根据条件模糊查询商品
     * @param condition
     */
    private void queryGoodsByCondition(String condition) {
        // TODO Auto-generated method stub
        OneApi.getGoodListByCondition(condition, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] arg1, byte[] responseBody) {
                Result result = GsonUtils.fromJson(new String(responseBody), Result.class);
                if (result.getCode() == 200) {
                    good_List = GsonUtils.json2List(result.getData(), Goods.class);
                    BigDecimal bd = new BigDecimal(total);
                    bd=bd.setScale(2, BigDecimal.ROUND_UP);
                    totalTv.setText("总金额(￥):"+bd+"");
                    adapter=new ShopGoodsAdapter(getActivity(), good_List,ShopGoodsAdapter.GOODS);
                    goodsLV.setAdapter(adapter);
                }
//                Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onFailure(int statusCode, Header[] arg1, byte[] responseBody, Throwable arg3) {
                Toast.makeText(getActivity(), "网络错误！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描回调
        if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
            String result = data.getStringExtra(SCAN_RESULT);

            Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
            queryField.setText(result);
        }
    }
    /**
     * 清空购物车
     */
    public void clearShoppingCart(){
        SharedPreferences mySharedPreferences = getActivity().getSharedPreferences("shoppingcart", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = mySharedPreferences.edit();
        editor.clear();
        editor.commit();
    }
}
